package com.whisperly.echotalk.account;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.appsflyer.AFInAppEventParameterName;
import com.appsflyer.AFInAppEventType;
import com.appsflyer.AppsFlyerLib;
import com.appsflyer.attribution.AppsFlyerRequestListener;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.material.snackbar.Snackbar;
import com.whisperly.echotalk.bllmodel.ChatHistory;
import com.whisperly.echotalk.bllmodel.CommonResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.UserQuery;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.schemas.SplashPage;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class Account extends AppCompatActivity {
    private GoogleSignInClient mGoogleSignInClient;
    private AlertDialog loadingDialog;
    private LinearLayout user_info,updatePws ,clearAccount;
    private TextView login_out;
    private Toast currentToast;
    private UserWithChat user = new UserWithChat();
    private static final String TAG = "Account";
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account);
        AppsManager.addActivity(this);

        // 初始化 Google Sign In Client
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        user = GlobalData.getUser();

        user_info = findViewById(R.id.user_info);
        user_info.setOnClickListener(v -> {
            if (GlobalData.getUsername().isEmpty()){
                showRegistrationAlertDialog();
            }else {
                Intent intent = new Intent(Account.this, AccountInfo.class);
                startActivity(intent);
            }
        });

        updatePws = findViewById(R.id.updatePws);
        updatePws.setOnClickListener(v -> {
            if (GlobalData.getUsername().isEmpty()){
                showRegistrationAlertDialog();
            }else {
                Intent intent = new Intent(Account.this, AccountPws.class);
                startActivity(intent);
            }

        });

        clearAccount = findViewById(R.id.clearAccount);
        clearAccount.setOnClickListener(v -> {
            if (GlobalData.getUsername().isEmpty()){
                showRegistrationAlertDialog();
            }else {
                verification();
            }
        });

        login_out = findViewById(R.id.login_out);
        if (GlobalData.getUsername().isEmpty()){
            login_out.setText(R.string.account_tips);
        }
        login_out.setOnClickListener(v -> {
            // 显示确认对话框
            showLogoutConfirmDialog();
        });
    }

    private void showLogoutConfirmDialog() {
        if (login_out.getText().equals(getString(R.string.account_tips))) {
            // 关闭所有活动并重新启动应用
            Intent intent = new Intent(this, Login.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_NEW_TASK |
                    Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            AppsManager.finishAll();
        }else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.Prompt)
                    .setMessage(R.string.confirm_logout)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        dialog.dismiss();
                        showLoadingDialog();
                        performLogout();
                    })
                    .setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss())
                    .setCancelable(false)
                    .show();
        }
    }

    private void showLoadingDialog() {
        View loadingView = getLayoutInflater().inflate(R.layout.loading_layout, null);
        loadingDialog = new AlertDialog.Builder(this)
                .setView(loadingView)
                .setCancelable(false)
                .create();

        // 设置对话框背景为圆角
        if (loadingDialog.getWindow() != null) {
            loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_round_corner);
        }

        loadingDialog.show();
    }

    private void performLogout() {
        // 检查是否是 Google 账号
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null) {
            // 如果是 Google 账号，先执行 Google 退出
            mGoogleSignInClient.signOut()
                    .addOnCompleteListener(this, task -> {
                        // Google 退出完成后执行本地退出
                        new Handler(Looper.getMainLooper()).postDelayed(this::completeLogout, 800); // 添加短暂延迟使动画更流畅
                    });
        } else {
            // 如果不是 Google 账号，直接执行本地退出
            new Handler(Looper.getMainLooper()).postDelayed(this::completeLogout, 800);
        }
    }

    private void completeLogout() {
        try {

            // 调用统一的退出方法
            SplashPage.logout(this);

            // 记录退出事件
            logLogoutEvent();

            // 显示成功提示
            showLogoutSuccessAndFinish();

        } catch (Exception e) {
            Log.e(TAG, "Error during logout", e);
            if (!isFinishing()) {
                // 如果发生错误，显示错误提示
                Snackbar.make(findViewById(android.R.id.content),
                        R.string.logout_error,
                        Snackbar.LENGTH_SHORT).show();
            }
        }
    }

    private void showLogoutSuccessAndFinish() {
        if (isFinishing()) return;

        // 关闭加载对话框
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }

        // 显示成功对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.success)
                .setMessage(R.string.logout_success)
                .setCancelable(false)
                .setPositiveButton(R.string.OK, (dialog, which) -> {
                    dialog.dismiss();
                    // 跳转到登录页面
                    Intent intent = new Intent(Account.this, Login.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                            Intent.FLAG_ACTIVITY_NEW_TASK |
                            Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                });

        AlertDialog successDialog = builder.create();
        successDialog.show();
    }

    private void logLogoutEvent() {
        try {
            Map<String, Object> eventValues = new HashMap<>();
            eventValues.put("logout", GlobalData.getUsername());
            AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                    "user_logout", eventValues, new AppsFlyerRequestListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(TAG, "Logout event sent successfully");
                        }
                        @Override
                        public void onError(int i, @NonNull String s) {
                            Log.d(TAG, "Logout event failed to be sent:\n" +
                                    "Error code: " + i + "\n" +
                                    "Error description: " + s);
                        }
                    });
        } catch (Exception e) {
            Log.e(TAG, "Error logging logout event", e);
        }
    }

    private void showRegistrationAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.login_is_required)
                .setMessage(R.string.login_is_required_message)
                .setPositiveButton(R.string.login, (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(this, Login.class);
                    startActivity(intent);
                    AppsManager.finishAll();
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(false)
                .show();
    }

    private void verification() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.verification, null);
        EditText etVerification = dialogView.findViewById(R.id.et_verification);
        ProgressBar progressBar = dialogView.findViewById(R.id.progressBar);
        progressBar.setVisibility(View.INVISIBLE);

        builder.setView(dialogView);
        builder.setTitle(R.string.cancel_account);
        builder.setMessage(R.string.cancel_account_message);
        builder.setPositiveButton(R.string.confirm, null);
        builder.setNegativeButton(R.string.cancel, null);
        builder.setCancelable(false);

        AlertDialog dialog = builder.create();
        dialog.setOnShowListener(dlg -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(view -> {
                String verification = etVerification.getText().toString().trim();

                if ("yes".equals(verification.toLowerCase(Locale.ROOT))) {

                    progressBar.setVisibility(View.VISIBLE);

                    UserWithChat userWithChat = new UserWithChat();
                    userWithChat.setObjectId(user.getObjectId());

                    NetworkUtils.getDelete(userWithChat.getObjectId(), new BlinkCallback() {
                        @Override
                        public void onSuccess(ResultBody<?> response) {
                            if (response.getCode() == 200){
                                CommonResponse data = (CommonResponse)response.getData();
                                if (data.getSuccess()){
                                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                                        progressBar.setVisibility(View.GONE);
                                        dialog.dismiss();
                                        if (currentToast != null) {
                                            currentToast.cancel();
                                        }
                                        currentToast = Toast.makeText(Account.this, R.string.cancel_account_tips, Toast.LENGTH_SHORT);
                                        currentToast.show();
                                        Map<String, Object> eventValues = new HashMap<String, Object>();
                                        eventValues.put("cancel-account", user.getName());

                                        AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                                                "cancel-account", eventValues,new AppsFlyerRequestListener() {
                                                    @Override
                                                    public void onSuccess() {
                                                        Log.d(TAG, "Event sent successfully");
                                                    }
                                                    @Override
                                                    public void onError(int i, @NonNull String s) {
                                                        Log.d(TAG, "Event failed to be sent:\n" +
                                                                "Error code: " + i + "\n"
                                                                + "Error description: " + s);
                                                    }
                                                });
                                        GlobalData.reset();
                                        Intent intent = new Intent(Account.this, Login.class);
                                        startActivity(intent);
                                        AppsManager.finishAll();
                                    }, 2000);
                                }else {
                                    currentToast = Toast.makeText(Account.this, R.string.cancel_account_tips2, Toast.LENGTH_SHORT);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            currentToast = Toast.makeText(Account.this, R.string.cancel_account_tips2, Toast.LENGTH_SHORT);
                        }
                    });
                } else {
                    if (currentToast!=null){
                        currentToast.cancel();
                    }
                    currentToast = Toast.makeText(this, R.string.cancel_account_tips3, Toast.LENGTH_SHORT);
                    currentToast.show();
                    etVerification.setError("'"+R.string.cancel_account_tips3+"'");
                    etVerification.setText("");
                }
            });

            Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            negativeButton.setOnClickListener(view -> dialog.dismiss());
        });

        dialog.show();
    }
}
